'use client'

import { useState, useEffect, useMemo } from "react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useLanguage } from "@/contexts/LanguageContext"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { ChevronDown, ChevronUp } from 'lucide-react'

interface Skill {
  id: string
  name: string
}

interface Course {
  id: string
  name: string
  skills: Skill[]
}

interface ScoreRecord {
  id: string
  student: string
  assignment: string
  courseId: string
  skillId: string
  score: number
  comment: string
}

interface GroupedScoreRecord {
  student: string
  courses: {
    id: string
    name: string
    skills: {
      id: string
      name: string
      assignments: {
        name: string
        score: number
        comment: string
      }[]
      averageScore: number
    }[]
    averageScore: number
  }[]
  averageScore: number
}

export function ScoreQuery() {
  const { t } = useLanguage()
  const [students, setStudents] = useState<string[]>([])
  const [assignments, setAssignments] = useState<string[]>([])
  const [courses, setCourses] = useState<Course[]>([])
  const [scoreRecords, setScoreRecords] = useState<ScoreRecord[]>([])

  const [selectedStudent, setSelectedStudent] = useState<string>("all")
  const [selectedCourse, setSelectedCourse] = useState<string>("all")
  const [selectedSkill, setSelectedSkill] = useState<string>("all")
  const [selectedAssignment, setSelectedAssignment] = useState<string>("all")
  const [expandedSkills, setExpandedSkills] = useState<Set<string>>(new Set());

  useEffect(() => {
    const savedStudents = JSON.parse(localStorage.getItem("students") || "[]")
    const savedAssignments = JSON.parse(localStorage.getItem("assignments") || "[]")
    const savedCourses = JSON.parse(localStorage.getItem("courses") || "[]")
    const savedScoreRecords = JSON.parse(localStorage.getItem("scoreRecords") || "[]")

    setStudents(savedStudents)
    setAssignments(savedAssignments)
    setCourses(savedCourses)
    setScoreRecords(savedScoreRecords)

    // Restore saved selections from localStorage
    const savedSelections = JSON.parse(localStorage.getItem("scoreQuerySelections") || "{}")
    setSelectedStudent(savedSelections.student || "all")
    setSelectedCourse(savedSelections.course || "all")
    setSelectedSkill(savedSelections.skill || "all")
    setSelectedAssignment(savedSelections.assignment || "all")
  }, [])

  useEffect(() => {
    // Save selections to localStorage
    const selectionsToSave = {
      student: selectedStudent,
      course: selectedCourse,
      skill: selectedSkill,
      assignment: selectedAssignment
    }
    localStorage.setItem("scoreQuerySelections", JSON.stringify(selectionsToSave))
  }, [selectedStudent, selectedCourse, selectedSkill, selectedAssignment])

  const groupedScoreRecords = useMemo(() => {
    const grouped: GroupedScoreRecord[] = []

    scoreRecords.forEach(record => {
      let studentGroup = grouped.find(g => g.student === record.student)
      if (!studentGroup) {
        studentGroup = { student: record.student, courses: [], averageScore: 0 }
        grouped.push(studentGroup)
      }

      let courseGroup = studentGroup.courses.find(c => c.id === record.courseId)
      if (!courseGroup) {
        const course = courses.find(c => c.id === record.courseId)
        courseGroup = { id: record.courseId, name: course?.name || '', skills: [], averageScore: 0 }
        studentGroup.courses.push(courseGroup)
      }

      let skillGroup = courseGroup.skills.find(s => s.id === record.skillId)
      if (!skillGroup) {
        const skill = courses.find(c => c.id === record.courseId)?.skills.find(s => s.id === record.skillId)
        skillGroup = { id: record.skillId, name: skill?.name || '', assignments: [], averageScore: 0 }
        courseGroup.skills.push(skillGroup)
      }

      skillGroup.assignments.push({ name: record.assignment, score: record.score, comment: record.comment })
    })

    // Calculate averages
    grouped.forEach(studentGroup => {
      let studentTotalScore = 0
      let studentTotalSkills = 0

      studentGroup.courses.forEach(courseGroup => {
        let courseTotalScore = 0
        let courseTotalSkills = 0

        courseGroup.skills.forEach(skillGroup => {
          const skillTotalScore = skillGroup.assignments.reduce((sum, assignment) => sum + assignment.score, 0)
          skillGroup.averageScore = skillGroup.assignments.length > 0 ? skillTotalScore / skillGroup.assignments.length : 0
          courseTotalScore += skillGroup.averageScore
          courseTotalSkills++
        })

        courseGroup.averageScore = courseTotalSkills > 0 ? courseTotalScore / courseTotalSkills : 0
        studentTotalScore += courseGroup.averageScore
        studentTotalSkills++
      })

      studentGroup.averageScore = studentTotalSkills > 0 ? studentTotalScore / studentTotalSkills : 0
    })

    return grouped
  }, [scoreRecords, courses])

  const filteredRecords = useMemo(() => {
    return groupedScoreRecords.filter(studentGroup => 
      (selectedStudent === "all" || studentGroup.student === selectedStudent)
    ).map(studentGroup => ({
      ...studentGroup,
      courses: studentGroup.courses.filter(courseGroup =>
        (selectedCourse === "all" || courseGroup.id === selectedCourse)
      ).map(courseGroup => ({
        ...courseGroup,
        skills: courseGroup.skills.filter(skillGroup =>
          (selectedSkill === "all" || skillGroup.id === selectedSkill)
        ).map(skillGroup => ({
          ...skillGroup,
          assignments: skillGroup.assignments.filter(assignment =>
            (selectedAssignment === "all" || assignment.name === selectedAssignment)
          )
        }))
      }))
    }))
  }, [groupedScoreRecords, selectedStudent, selectedCourse, selectedSkill, selectedAssignment])

  const averageScore = useMemo(() => {
    if (filteredRecords.length === 0) return null

    const allCourseAverages = filteredRecords.flatMap(studentGroup => 
      studentGroup.courses.map(courseGroup => courseGroup.averageScore)
    )

    return allCourseAverages.length > 0 
      ? allCourseAverages.reduce((sum, score) => sum + score, 0) / allCourseAverages.length 
      : null
  }, [filteredRecords])

  const exportToCSV = () => {
    const csvContent = "data:text/csv;charset=utf-8," 
      + filteredRecords.flatMap(studentGroup => 
          studentGroup.courses.flatMap(courseGroup => 
            courseGroup.skills.flatMap(skillGroup => 
              skillGroup.assignments.map(assignment => 
                [
                  studentGroup.student,
                  courseGroup.name,
                  skillGroup.name,
                  assignment.name,
                  assignment.score,
                  assignment.comment
                ].join(",")
              )
            )
          )
        ).join("\n")
    
    const encodedUri = encodeURI(csvContent)
    const link = document.createElement("a")
    link.setAttribute("href", encodedUri)
    link.setAttribute("download", "score_records.csv")
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  const toggleSkillExpansion = (skillId: string) => {
    setExpandedSkills(prev => {
      const newSet = new Set(prev);
      if (newSet.has(skillId)) {
        newSet.delete(skillId);
      } else {
        newSet.add(skillId);
      }
      return newSet;
    });
  };

  return (
    <div className="space-y-6">
      <h2 className="text-2xl font-bold">{t("评分查询")}</h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Select value={selectedStudent} onValueChange={setSelectedStudent}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择同学")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("全部同学")}</SelectItem>
            {students.map((student) => (
              <SelectItem key={student} value={student}>
                {student}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={selectedCourse} onValueChange={setSelectedCourse}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择课程")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("全部课程")}</SelectItem>
            {courses.map((course) => (
              <SelectItem key={course.id} value={course.id}>
                {course.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={selectedSkill} onValueChange={setSelectedSkill}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择技能")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("全部技能")}</SelectItem>
            {courses.flatMap(course => course.skills).map((skill) => (
              <SelectItem key={skill.id} value={skill.id}>
                {skill.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={selectedAssignment} onValueChange={setSelectedAssignment}>
          <SelectTrigger>
            <SelectValue placeholder={t("选择作业")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("全部作业")}</SelectItem>
            {assignments.map((assignment) => (
              <SelectItem key={assignment} value={assignment}>
                {assignment}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Card>
        <CardHeader>
          <CardTitle>{t("平均分")}</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-3xl font-bold">
            {averageScore !== null ? averageScore.toFixed(2) : t('暂无数据')}
          </p>
        </CardContent>
      </Card>
      <div>
        <h3 className="text-xl font-semibold mb-4">{t("评分记录")}</h3>
        <Button onClick={exportToCSV} className="mb-4">{t("导出CSV")}</Button>
        <Accordion type="single" collapsible className="w-full">
          {filteredRecords.map((studentGroup) => (
            <AccordionItem key={studentGroup.student} value={studentGroup.student}>
              <AccordionTrigger>
                {t("同学")}: {studentGroup.student} - {t("平均分")}: {studentGroup.averageScore.toFixed(2)}
              </AccordionTrigger>
              <AccordionContent>
                {studentGroup.courses.map((courseGroup) => (
                  <Accordion key={courseGroup.id} type="single" collapsible className="w-full ml-4 mt-2">
                    <AccordionItem value={courseGroup.id}>
                      <AccordionTrigger>
                        {t("课程")}: {courseGroup.name} - {t("平均分")}: {courseGroup.averageScore.toFixed(2)}
                      </AccordionTrigger>
                      <AccordionContent>
                        {courseGroup.skills.map((skillGroup) => (
                          <Collapsible key={skillGroup.id} className="ml-4 mt-2">
                            <CollapsibleTrigger onClick={() => toggleSkillExpansion(skillGroup.id)} className="flex items-center justify-between w-full text-left font-semibold">
                              <span>{t("技能")}: {skillGroup.name} - {t("平均分")}: {skillGroup.averageScore.toFixed(2)}</span>
                              {expandedSkills.has(skillGroup.id) ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                            </CollapsibleTrigger>
                            <CollapsibleContent>
                              <Table>
                                <TableHeader>
                                  <TableRow>
                                    <TableHead>{t("作业")}</TableHead>
                                    <TableHead>{t("评分")}</TableHead>
                                    <TableHead>{t("评语")}</TableHead>
                                  </TableRow>
                                </TableHeader>
                                <TableBody>
                                  {skillGroup.assignments.map((assignment, index) => (
                                    <TableRow key={index}>
                                      <TableCell>{assignment.name}</TableCell>
                                      <TableCell>{assignment.score}</TableCell>
                                      <TableCell>{assignment.comment}</TableCell>
                                    </TableRow>
                                  ))}
                                </TableBody>
                              </Table>
                            </CollapsibleContent>
                          </Collapsible>
                        ))}
                      </AccordionContent>
                    </AccordionItem>
                  </Accordion>
                ))}
              </AccordionContent>
            </AccordionItem>
          ))}
        </Accordion>
      </div>
    </div>
  )
}

